package com.iflysse.controller;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.iflysse.consts.ResultEnum;
import com.iflysse.consts.RoleEnum;
import com.iflysse.dto.UserLoginDto;
import com.iflysse.entity.Account;
import com.iflysse.service.AccountService;
import com.iflysse.utils.CommonUtil;
import com.iflysse.utils.JwtUtil;
import com.iflysse.vo.AjaxResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(tags = { "用户登录接口" })
@RestController
@RequestMapping("/user")
public class LoginController {
	
	private final static Log log = LogFactory.getLog(LoginController.class);
	
	@Autowired
	private AccountService accountService;
	@ApiOperation(value = "登录")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "userName", dataType = "String", required=true, value="用户名"), 
		@ApiImplicitParam(paramType = "query", name = "passWord", dataType = "String", required=true, value="用户密码"),
		@ApiImplicitParam(paramType = "query", name = "code", dataType = "int", required=true, value="验证码"), 
		@ApiImplicitParam(paramType = "query", name = "codeId", dataType = "String", required=true, value="验证码ID")
	})
	@PostMapping("/login")
	public AjaxResult login(@Valid UserLoginDto form, HttpServletRequest request) throws Exception {

		log.info("登录接口的前端请求参数bean:" + form);
		// 校验验证码是否正确
		String sessionCode = (String) request.getSession().getAttribute(form.getCodeId());
		if (!form.getCode().equals(sessionCode)) {
			return new AjaxResult(ResultEnum.CODEERROR.getCode(), ResultEnum.CODEERROR.getMsg());
		}

		Account account = accountService.login(form);
		if (account == null || account.getAccountId() == null || account.getRole() == null) {
			return new AjaxResult(ResultEnum.ACCOUNTERROR.getCode(), ResultEnum.ACCOUNTERROR.getMsg());
		}

		// 根据accountId和角色生成token信息
		String token = JwtUtil.createToken(account.getAccountId(), account.getRole().toString());

		// 根据userBoResp 中的userId(账户编号)和角色查询对应的老师编号或者学生编号
		String userId = accountService.queryIdByAccountIdAndRole(account.getAccountId(), account.getRole().toString());

		// TODO 完成封装数据并返回
		
        Map codeResp = new HashMap();
        codeResp.put("role", account.getRole().toString() );
        codeResp.put("token", token);
        codeResp.put("userId", userId);
        AjaxResult result = AjaxResult.success(codeResp);
		
		
		return result;
	}
	@ApiOperation(value = "验证码")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "request" ), 
		@ApiImplicitParam(name = "response")
	})
	@PostMapping("/code")
	public AjaxResult createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //创建一张缓存图片
        BufferedImage image=new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);

        //根据图片对象获取出图片的绘制对象
        Graphics g=image.getGraphics();
        //根据绘制对象来给图片增加背景颜色
        g.setColor(Color.WHITE);
        //根据绘制对象来确定背景颜色的范围
        g.fillRect(0,0 , 100, 30);

        //往这张图片画的东西（干扰线，数字）

        g.setColor(Color.YELLOW);
        //随机生成一个数
        Random r=new Random();       
        for(int i=0;i<20;i++) {
            int x1=r.nextInt(90);
            int y1=r.nextInt(30);
            int newX=r.nextInt(90);
            int newY=r.nextInt(30);
            //画干扰线
            g.drawLine(x1, y1, newX, newY);
        }

        //往图片中绘制验证码
        g.setColor(Color.GREEN);

        //便生成随机验证码边绘制到图片中
        String sbCode = CommonUtil.genCode(4);
        int x=20;
        for(int i=0;i<sbCode.length();i++) {
            g.drawString(""+sbCode.charAt(i), x, 20);//
            x=x+20;
        }

        // 生成验证码的唯一标识
        String codeId= UUID.randomUUID().toString().replaceAll("-","");

        log.info("验证码编号："+codeId+"对应的验证码为："+sbCode);
        //设置session的有效期
        //将验证码存到session中，方便登录时来获取这个验证去校验用户登陆时所输入的验证码是否正确
        HttpSession session=request.getSession();
//        session.setMaxInactiveInterval(300);//5分钟有效
        session.setAttribute(codeId, sbCode.toString());
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        ImageIO.write(image, "gif", baos);//写入流中
        byte[] bytes = baos.toByteArray();//转换成字节

        Base64.Encoder base64=Base64.getEncoder();

        byte [] img= base64.encode(bytes);

        String png_base64=new String(img);
        //删除 \r\n
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");

        log.debug("验证码"+sbCode+"，对应的base64码："+png_base64);

        //封装数据并返回
        Map codeResp = new HashMap();
        codeResp.put("codeId", codeId);
        codeResp.put("baseImage", CommonUtil.appendBaseToWebApp(png_base64,"gif"));
        AjaxResult result = AjaxResult.success(codeResp);
        return result;

    }
}

